package com.ruoyi.client.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.client.service.ShoppingService;
import com.ruoyi.client.utils.HttpClientUtils;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.recycle.domain.*;
import com.ruoyi.recycle.dto.ClientPrayerManagementQuery;
import com.ruoyi.recycle.dto.HomePageSlideshowDTO;
import com.ruoyi.recycle.mapper.IntegralOrderMapper;
import com.ruoyi.recycle.service.*;
import com.ruoyi.recycle.service.IShopManagementService;
import com.ruoyi.recycle.utils.OssUpload;
import com.ruoyi.system.api.util.WxPhoneUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户端小程序首页相关Controller
 *
 * @author Wubk
 * @date 2022-05-22
 */
@RestController
@RequestMapping("/home")
@Api(tags = "客户端小程序首页相关")
@Slf4j
public class HomeController extends BaseController {

    @Resource
    private IShopManagementService shopManagementService;
    @Resource
    private IClientUserManagementService clientUserManagementService;
    @Resource
    private IMerchantManagementService merchantManagementService;
    @Resource
    private ISysTypeConfigService sysTypeConfigService;
    @Resource
    private IHomePageSlideshowService homePageSlideshowService;
    @Resource
    private IRecycleHandbookService recycleHandbookService;
    @Resource
    private IFeedbackService feedbackService;
    @Resource
    private ShoppingService shoppingService;

    /**
     * 分页条件查询 平台宣传海报
     */
    @PostMapping("/slideshowPageQuery")
    @ApiOperation("分页条件查询 平台宣传海报")
    public IPage<HomePageSlideshow> slideshowPageQuery(@RequestBody HomePageSlideshowDTO queryDTO) {
        final HomePageSlideshow slideshow = new HomePageSlideshow();
        BeanUtils.copyProperties(queryDTO, slideshow);
        final LambdaQueryWrapper<HomePageSlideshow> wrapper = Wrappers.lambdaQuery(slideshow);
        if (queryDTO.getSearchTimeBegin() != null) {
            wrapper.ge(HomePageSlideshow::getCreatedTime, queryDTO.getSearchTimeBegin());
        }
        if (queryDTO.getSearchTimeEnd() != null) {
            wrapper.le(HomePageSlideshow::getCreatedTime, queryDTO.getSearchTimeEnd());
        }
        wrapper.orderByDesc(HomePageSlideshow::getCreatedTime);
        return homePageSlideshowService.page(new Page<HomePageSlideshow>()
                .setCurrent(queryDTO.getCurrentPage())
                .setSize(queryDTO.getPageSize()), wrapper);
    }


    /**
     * 获取附近的推荐门店
     * double dis         距离，
     * double longitude  定位的经度，
     * double latitude   定位的纬度。
     *
     * @return
     */
    @PostMapping("/nearbyShopRecommend")
    @ApiOperation("获取附近的推荐门店")
    public AjaxResult nearbyShopRecommend(@RequestParam(value = "dis", required = true) Double dis,
                                          @RequestParam(value = "longitude", required = true) Double longitude,
                                          @RequestParam(value = "latitude", required = true) Double latitude,
                                          @RequestParam(value = "clientId", required = true) Long clientId) {

        return shopManagementService.nearbyShopRecommend(dis, longitude, latitude, clientId);
    }


    /**
     * 获取附近的推荐门店-店名模糊匹配
     * double dis         距离，
     * double longitude  定位的经度，
     * double latitude   定位的纬度。
     *
     * @return
     */
    @PostMapping("/selectShopByName")
    @ApiOperation("获取附近的推荐门店-店名模糊匹配")
    public AjaxResult nearbyShopRecommend(@RequestParam(value = "dis", required = true) Double dis,
                                          @RequestParam(value = "longitude", required = true) Double longitude,
                                          @RequestParam(value = "latitude", required = true) Double latitude,
                                          @RequestParam(value = "name", required = false) String name,
                                          @RequestParam(value = "clientId", required = true) Long clientId,
                                          @RequestParam(value = "type", required = false) String type) {

        return shopManagementService.nearbyShopRecommend(dis, longitude, latitude, name, clientId, type);
    }

    /**
     * 获取附近的推荐门店-店名模糊匹配
     * double dis         距离，
     * double longitude  定位的经度，
     * double latitude   定位的纬度。
     *
     * @return
     */
    @PostMapping("/selectShopById")
    @ApiOperation("根据ID获取门店信息")
    public AjaxResult selectByClientIdAndShopIdGetShopDetail(@RequestParam(value = "shopId", required = true) Long shopId,
                                                             @RequestParam(value = "clientId", required = true) Long clientId,
                                                             @RequestParam(value = "longitude", required = true) Double longitude,
                                                             @RequestParam(value = "latitude", required = true) Double latitude) {

        return shopManagementService.selectByClientIdAndShopIdGetShopDetail(shopId, clientId,longitude,latitude);
    }

    /***
     * 获取客户地址列表
     */
    @PostMapping("/getClientAddress")
    @ApiOperation("获取客户地址列表")
    public AjaxResult getClientAddress(@RequestParam(value = "clientId", required = true) Integer clientId) {
        return clientUserManagementService.getClientAddress(clientId);
    }


    /**
     * 获取推荐综合站
     * double dis         距离，
     * double longitude  定位的经度，
     * double latitude   定位的纬度。
     *
     * @return
     */
    @GetMapping("/nearbyMerchantRecommend")
    public AjaxResult nearbyMerchantRecommend(@RequestParam(value = "dis", required = true) Double dis,
                                              @RequestParam(value = "longitude", required = true) Double longitude,
                                              @RequestParam(value = "latitude", required = true) Double latitude) {

        return merchantManagementService.nearbyMerchantRecommend(dis, longitude, latitude);
    }

    /**
     * 一键回收获取信息
     */
    @GetMapping("/oneKeyRecycle/{id}")
    public AjaxResult oneKeyRecycle(@PathVariable("id") Long id) {
        return sysTypeConfigService.oneKeyRecycle(id);
    }


    /**
     * 新增客户保存
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增客户", notes = "新增客户")
    public AjaxResult save(@RequestBody ClientUserManagement clientClient) {

        if (ObjectUtils.isNotEmpty(clientClient) && clientClient.getParentId() != null && clientClient.getParentId() != 0) {

            List<ClientUserManagement> list = clientUserManagementService.list(new LambdaQueryWrapper<>(new ClientUserManagement()).
                    eq(ClientUserManagement::getOpenid, clientClient.getOpenid()).
                    eq(ClientUserManagement::getParentId, clientClient.getParentId()));

            if (list.size() > 0) {
                return AjaxResult.success().put("success", "已存在小学生用户");
            }
        } else {

            List<ClientUserManagement> list = clientUserManagementService.list(new LambdaQueryWrapper<>(new ClientUserManagement()).eq(ClientUserManagement::getOpenid, clientClient.getOpenid()));

            if (list.size() > 0) {
                return AjaxResult.success().put("success", "会员已存在");
            }
        }
        //TODO 数据初始化时，初始化话一个0号客户，用于提供默认头像照片
        ClientUserManagement byId = clientUserManagementService.getById(0);
        clientClient.setImg(byId.getImg());
        clientClient.setCreatedTime(new Date());
        clientUserManagementService.save(clientClient);

        return AjaxResult.success();
    }

    /**
     * 小程序登录
     */
    @GetMapping("/login")
    @ResponseBody
    @ApiOperation(value = "小程序登录", notes = "小程序登录")
    public AjaxResult mini_Login(HttpServletRequest request, @Param("code") String code) {
        String co = request.getParameter("code");//也可以通过此语句获取code值

        return clientUserManagementService.login(code);
    }

    @ApiOperation(value = "获取手机号", notes = "获取手机号并新增会员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "encryptedData", value = "encryptedData", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "iv", value = "iv", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "session_key", value = "session_key", required = true, paramType = "query", dataType = "string"),
    })
    @GetMapping("/getUserPhone")
    public AjaxResult getUserPhone(@RequestParam("encryptedData") String encryptedData, @RequestParam("iv") String iv, @RequestParam("session_key") String session_key) {
        try {
            System.out.println("encryptedData = " + encryptedData + "iv = " + iv + "session_key = " + session_key);

            String relust = WxPhoneUtil.decryptData(encryptedData, session_key, iv);
            Map<String, Object> map = JSON.parseObject(relust, HashMap.class);

            if (StringUtils.isBlank(String.valueOf(map.get("phoneNumber")))) {
                return AjaxResult.error("无法获取用户绑定手机号码");
            }

            return AjaxResult.success().put("phoneNumber", String.valueOf(map.get("phoneNumber")));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("系统出错");
        }

    }


    @PostMapping("/handbookList")
    @ApiOperation("查询回收指南列表")
    public TableDataInfo list(@RequestParam("handbookType") String handbookType) {
        startPage();
        RecycleHandbook recycleHandbook = new RecycleHandbook();
        recycleHandbook.setHandbookType(handbookType);
        List<RecycleHandbook> list = recycleHandbookService.selectRecycleHandbookList(recycleHandbook);
        return getDataTable(list);
    }

    @Log(title = "意见反馈", businessType = BusinessType.INSERT)
    @PostMapping("/saveFeedback")
    @ApiOperation("新增意见反馈")
    public AjaxResult add(@RequestBody Feedback feedback) {
        return toAjax(feedbackService.insertFeedback(feedback));
    }


    @PostMapping("/exportImport")
    @ApiOperation(value = "图片上传")
    @ApiResponses({
            @ApiResponse(code = 200, message = "失败抛出异常"),
    })
    @ApiImplicitParam(name = "file", dataType = "MultipartFile")
    public R exportImport(@RequestParam("file") MultipartFile file) {
        try {
            String sux = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
            String s = OssUpload.uploadFile(file, sux);
            return R.ok(s);
        } catch (Exception ex) {
            return R.fail("图片上传失败！");
        }
    }

    /**
     * 根据经纬度查询国家-省份-城市
     * double longitude  定位的经度，
     * double latitude   定位的纬度。
     *
     * @return
     */
    @PostMapping("/selectCityName")
    public AjaxResult selectCityName(@RequestParam(value = "longitude", required = true) Double longitude,
                                     @RequestParam(value = "latitude", required = true) Double latitude) {

        try {
            Map<String, Object> byLatAndLng = HttpClientUtils.findByLatAndLng(latitude.toString(), longitude.toString());

            Map<String, Object> cityMap = new HashMap<>();
            if (byLatAndLng.get("status").equals(0)) {
                Map<String, Object> resultMap = (Map<String, Object>) byLatAndLng.get("result");
                resultMap = (Map<String, Object>) resultMap.get("addressComponent");
                cityMap.put("country", (String) resultMap.get("country"));
                cityMap.put("province", (String) resultMap.get("province"));
                cityMap.put("city", (String) resultMap.get("city"));
            }

            return AjaxResult.success(cityMap);
        } catch (Exception e) {
            log.error("经纬度获取失败{}", e.getMessage(), e);
            return AjaxResult.error("经纬度获取城市异常，请联系管理员处理");
        }
    }

    /**
     * 获取当前系统回收总数量
     */
    @GetMapping("/getTotalRecycleOrder")
    public AjaxResult getTotalRecycleOrder() {
        return shoppingService.getTotalRecycleOrder();
    }

    /**
     * 滚动显示用户全部许愿信息
     */
    @GetMapping("/prayerList")
    @ApiOperation("滚动显示用户全部许愿信息")
    public AjaxResult prayerList(){
        return AjaxResult.success(shoppingService.prayerList());
    }

}
